;
(function() {
  var ACCOUNTID = hlUrlUtil.GetQueryString('id'); //账单id
  var CONTRACTID = hlUrlUtil.GetQueryString('aid'); //合同id
  var PAGE = hlUrlUtil.GetQueryString('page'); //合同id
  var permissions = window.localStorage.getItem('permissions') //page

  Array.prototype.removeRepeatBuildingAndFLoor = function() {
    var res = [this[0]];
    for (var i = 1; i < this.length; i++) {
      var repeat = false;
      for (var j = 0; j < res.length; j++) {
        if (this[i].buildingName == res[j].buildingName && this[i].floorNum == res[j].floorNum) {
          repeat = true;
        }
      }
      if (!repeat) {
        res.push(this[i]);
      }
    }
    return res;
  };

  new Vue({
    el: '#bill-detail',
    data: {
      idA: {
        ida: ACCOUNTID,
        idb: CONTRACTID
      },
      contractData: {
        ot: [],
        st: []
      },
      billData: {
        expenses: [],
        transactions: [],
        invoiceInfos: [],
				carryOverInfos: [],
				waTransactions: []
      },
      editFlag: true,
      temporary: 0,
      permissions: JSON.parse(permissions),
      costItem: [],
      fPData: [],
      fpPut: [],
      fpFlag: false,
      closeFlag: false,
      memo: {
        content: '',
        flag: false
      },
      proid: '',
      fPIS: 0,
      NIS: 0,
      plFp: 0,
      Fp: [],
      jlFp: [],
      page: PAGE,
      st: [], // 车位
      wp: [], // 工位
      stTotalNum: 0, // 车位总数
      wpTotalNum: 0, // 工位总数
      totalArea: 0, // 单元总面积
      building: [], // 楼宇信息
      projectName: null, // 项目名
      unitOpenFlag: false,
      wpOpenFlag: false,
      stOpenFlag: false,
      CZOpenFlag: false,
      printflag: true,
      isEditCountMes: false,
      receiptDeadlineDate: null,
      logData: [],
			IsCompareRentAmtFlag: false,
			// 20190617
			billReasonFlag: false,
			billOperate: '审核通过',
			placeholderBill: '',
			refusalToPassReason: ''
    },
    filters: {
      timestamp: function(time) {
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      billState: function(state) {
        if (!state) return '';
        return hlCodeConvert.billPaymentState(state)
      },
      toFixed2: function(n) {
        return Number(n).toFixed(2)
      },
      billPayWay: function(state) {
        return hlCodeConvert.billPayWay(state)
      },
      //千分位
      formatNum: function(n) {
        return hlNumberUtil.formatNum(n)
      },
      absNum: function(n) {
        return Math.abs(n)
      }
    },
    computed: {
      temporarys: function() {
        for (var i = 0; i < this.billData.expenses.length; i++) {
          if (this.billData.expenses[i].expenseType === 'T') {
            this.temporary++
          }
        }
        return this.temporary
      },
      fPDataNum: function() {
        var result = 0;
        for (var i = 0; i < this.fPData.length; i++) {
          if (this.fPData[i].expenseType === 'T') {
            result++
          }
        }
        return result
      },
      //应收本金
      totalYS: function() {
        var result = 0; //总和
        var IS = 0; //已收款
        this.billData.expenses.map(function(item) {
          if (Number(item.amountReceived) > 0) {
            result += Number(item.amountReceived)
          }
        })
        return result
      },
      //已收本金
      totalIS: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
      		result += Number(item.amountPayed);          
        })
        return result
      },
      //减免本金
      totalJM: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
      		result += Number(item.amountDerate);         
        })
        return result
      },
      //结转抵扣 (应收)
      carryOverTotalAmount: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
      		if (item.carryOverTotalAmount > 0 && item.amountReceived > 0) {
      			result += Number(item.carryOverTotalAmount);
      		}          
        })
        return result
      },
      //本次应收本金
      totalBCYS: function() {
        var result = 0; //总和
        result = this.totalYS - this.totalIS - this.totalJM - this.carryOverTotalAmount;
        return result
      },
      //本次应收滞纳金
      totalYSznj: function() {
        var result = 0; //总和
        var IS = 0; //已收款
        this.billData.expenses.map(function(item) {
          result += Number(item.lateFeeReceived)
        })
        return result
      },
      //已收滞纳金
      totalISznj: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
          result += Number(item.lateFeePayed);
        })
        return result
      },
      //减免滞纳金
      totalJMznj: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
          result += Number(item.lateFeeDerate);
        })
        return result
      },
      //本次应收滞纳金
      totalBCYSznj: function() {
        var result = 0; //总和
        result = this.totalYSznj - this.totalISznj - this.totalJMznj;
        return result
      },
      //本次应退
      totalYT: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
          result += Math.abs(Number(item.amountRefund))
        })
        return result
      },
      //已退本金
      totalIT: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
          result += Math.abs(Number(item.refundPayed))
        })
        return result
      },
      //结转抵扣 (应退)
      carryOverTotalAmountYt: function() {
        var result = 0; //总和
        this.billData.expenses.map(function(item) {
        	if (item.amountReceived < 0 && item.expenseType == 'T') {
        		result += Math.abs(item.carryOverTotalAmount);
        	}          
        })
        return result
      },
      //本次应退
      totalBCYT: function() {
        var result = 0; //总和
        result = this.totalYT - this.totalIT - this.carryOverTotalAmountYt
        return result
      },
      //本次应收合计
      totalYSHJ: function() {
        var result = 0; //总和
        result = this.totalBCYS + this.totalBCYSznj - this.totalBCYT;
      	if (this.totalNum == 1) {
      	  this.txs[0]['amountTPay'] = Number(result).toFixed(2);
      	}
      	this.totalNum++;
        return Number(result).toFixed(2)
      },
      
      cumulation: function() {
        var result = 0;
        this.txs.map(function(item) {
          result += Number(hlNumberUtil.formatThousandsNum(item.amountTPay))
        })
        return Number(result).toFixed(2);
      },
			
			//审核实收金额
			avAmount () {
				let res = 0;
				this.billData.waTransactions.map(function(item) {
					res += Number(item.amountTPay)          
				})
				return res
			}
    },
    methods: {  
			// 20190617
			closeDialog () {
				this.billReasonFlag = false
			},
			approvalButton (text) {
				this.billReasonFlag = true;
				this.billOperate = text;
				this.refusalToPassReason = '';
				if (text == '审核通过') {this.placeholderBill = '审核通过原因说明（非必填）'}
				if (text == '审核拒绝') {this.placeholderBill = '审核拒绝原因说明（必填）'}
			},
			//确认
			querySubmit () {
				if (this.billOperate == '审核通过') { this.refusal() }
				if (this.billOperate == '审核拒绝') { 
					if (!this.refusalToPassReason.length) {
						hl.toast('审核拒绝原因不能为空')
						return
					}
					this.pass()
				}
				this.closeDialog()
			},
			//通过
			refusal () {
				hlhttp.put({
					url: 'bill/_pass',
					data: { bill_id: ACCOUNTID, memo: this.refusalToPassReason || '#' },
					success: () => {
						hlUrlUtil.goTo('billDetail',{'page': PAGE, id: ACCOUNTID, aid: CONTRACTID, ddtab:true})
					}
				})
			},
			//拒绝
			pass () {
				hlhttp.put({
					url: 'bill/_reject',
					data: { bill_id: ACCOUNTID, memo: this.refusalToPassReason || '#' },
					success: () => {
						hlUrlUtil.goTo('billDetail',{'page': PAGE, id: ACCOUNTID, aid: CONTRACTID, ddtab:true})
					}
				})
			},
			//end
      // 获取合同单元信息
      getContractUnitsData: function() {
        var self = this;
        hlhttp.get({
          url: 'contract/units',
          data: {
            id: CONTRACTID
          },
          success: function(data) {
            // 单元
            var buildingData = self.dealWithUnitData(data)
            self.totalArea = buildingData.totalArea
            self.building = buildingData.building
            // 车位
            self.st = [];
            self.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            data.map(function(item) {
              if (item.positions && item.unitType === 'ST') {
                stTotalNum = stTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.st.push(item)
              }
              if (item.positions && item.unitType === 'WP') {
                wpTotalNum = wpTotalNum + item.positions.length;
                item['num'] = item.positions.length;
                self.wp.push(item)
              }
            })
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      // 单元数据去重整合处理
      dealWithUnitData: function(unitsData) {
        // 去除含有工位车位的单元
        var units = [];
        unitsData.map(function(_item) {
          if (_item.positions.length === 0) {
            units.push(_item)
          }
        })
        if (units.length === 0) {
          return {
            building: [],
            totalArea: 0
          }
        }
        // 合并单元项
        var unit = [];
        var totalArea = 0;
        for (var i = 0; i < units.length; i++) {
          unit.push({
            buildingName: units[i].buildingName,
            floorNum: units[i].floorNum,
            floorName: units[i].floorName,
            unit: []
          })
        }
        var unitArr = unit.removeRepeatBuildingAndFLoor()
        for (var z = 0; z < unitArr.length; z++) {
          for (var m = 0; m < units.length; m++) {
            if (units[m].buildingName == unitArr[z].buildingName && units[m].floorNum == unitArr[z].floorNum) {
              unitArr[z].unit.push(units[m].unitName + '(' + hlNumberUtil.formatNum(units[m].unitAcreage) + 'm²)')
              totalArea = totalArea + Number(units[m].unitAcreage)
            }
          }
        }
        // 合并楼层项
        var building = [];
        for (var j = 0; j < unitArr.length; j++) {
          building.push({
            buildingName: unitArr[j].buildingName,
            floor: []
          })
        }
        var buildingArr = hlArrayUtil.removeRepeat(building, 'buildingName')
        for (var k = 0; k < buildingArr.length; k++) {
          for (var n = 0; n < unitArr.length; n++) {
            if (unitArr[n].buildingName == buildingArr[k].buildingName) {
              buildingArr[k].floor.push({
                'floorNum': unitArr[n].floorNum,
                'floorName': unitArr[n].floorName,
                'unit': unitArr[n].unit
              })
            }
          }
        }
        return {
          building: buildingArr,
          totalArea: totalArea
        }
      },
      // 查看出租资源详情信息
      checkDetailMes: function(type) {
        var self = this;
        if (type === 'unit') {
          if (self.unitOpenFlag === true) {
            self.unitOpenFlag = false
            return false
          }
          if (self.unitOpenFlag === false) {
            self.unitOpenFlag = true
            return false
          }
        }
        if (type === 'wp') {
          if (self.wpOpenFlag === true) {
            self.wpOpenFlag = false;
            return false;
          }
          if (self.wpOpenFlag === false) {
            self.wpOpenFlag = true
            return false;
          }
        }
        if (type === 'st') {
          if (self.stOpenFlag === true) {
            self.stOpenFlag = false
            return false;
          }
          if (self.stOpenFlag === false) {
            self.stOpenFlag = true
            return false;
          }
        }
      },
      //获取合同信息
      getContractData: function() {
        var _this = this;
        contract.formatUnitData(CONTRACTID, function(data) {
          _this.contractData = data
        })
      },
			//跳转营业额详情
			gotoCommisson () {
				hlUrlUtil.goTo('commissionDetail',{'id': ACCOUNTID, ddtab:true})
			},
      //获取意向详情
      getYxInfo(id) {
        var self = this;
        hlhttp.get({
          url: 'contract/intent',
          data: {
            id: id
          },
          success: (data) => {
            data.projectInfo.units.map(item => {
              item.positions = [];
              item.floorName = item.floorNum
            })
            this.contractData.zlfCompany = data.zlfInfo.zlfName
            this.contractData.projectName = data.projectInfo.projectName
            var buildingData = this.dealWithUnitData(data.projectInfo.units)
            this.totalArea = buildingData.totalArea
            this.building = buildingData.building;
            this.printflag = false;
            // this.billData.billTypeName = data.intentTypeVal;
            this.st = [];
            this.wp = [];
            var stTotalNum = 0;
            var wpTotalNum = 0;
            //车位
            let newStArr = hlArrayUtil.removeRepeat(data.projectInfo.stops, 'unitId'),
              newStIds = [];
            newStArr.map(item => {
              item.floor = item.floorNum;
              item.floorName = item.floorNum
              item.positions = []
            })
            data.projectInfo.stops.map(item => {
              newStIds.push(item.stopId)
              newStArr.map(item1 => {
                if (item.unitId == item1.unitId) {
                  stTotalNum++
                  item1.positions.push({
                    positionName: item.stopName,
                    positionId: item.stopId
                  })
                }
              })
            })
            self.st = newStArr;
            let newWpArr = hlArrayUtil.removeRepeat(data.projectInfo.wps, 'unitId'),
              newWpIds = [];
            newWpArr.map(item => {
              item.floor = item.floorNum
              item.positions = []
            })
            data.projectInfo.wps.map(item => {
              newWpIds.push(item.wpId)
              newWpArr.map(item1 => {
                if (item.unitId == item1.unitId) {
                  wpTotalNum++
                  item1.positions.push({
                    positionName: item.wpName,
                    positionId: item.wpId
                  })
                }
              })
            })
            this.wp = newWpArr
            self.stTotalNum = stTotalNum;
            self.wpTotalNum = wpTotalNum;
          }
        })
      },
      //获取账单信息
      getBillData: function() {
        var _this = this;
        hlhttp.get({
          url: 'bill,expenses,transactions',
          data: {
            bill_id: ACCOUNTID
          },
          success: function(data) {
            if (data.intentId) {
              _this.getYxInfo(data.intentId)
            }
            CONTRACTID = data.contractId
            if (CONTRACTID) {
              _this.getContractData()
            }
												
						if (!data.waTransactions) {
							data.waTransactions = []
						}
						
						data.waTransactions.map(item => {
							item.imgs = item.vouchers ? item.vouchers.split(',') : []
						})
						
            _this.billData = data;
						console.log(_this.billData)
            _this.proid = data.projectId;
            for (var i = 0; i < _this.billData.transactions.length; i++) {
              _this.billData.transactions[i].flag = false;
              _this.Fp.push({
                index: '',
                id: '',
                flag: ''
              })
            }           

            _this.receiptDeadlineDate = hlDateUtil.formatUTCDate(data.deadlineDate, 'yyyy-MM-dd')
          }
        })
      },
      //获取日志详情
      getlogData() {
        var that = this
        hlhttp.get({
          url: 'bill/logs',
          data: {
            bill_id: ACCOUNTID
          },
          success: function(data) {
            that.logData = data.groupLogs
            that.logData.forEach(item => {
              if (item.operationName == '编辑账单费项') {
                item.logRecords.forEach(item1 => {
                  item1.list = []
                  for (var i = 0; i < item1.rowData.length; i += 3) {
                    item1.list.push(item1.rowData.slice(i, i + 3));
                  }
                })
              }
            })
          }
        })
      },
      
      //获取待分配
      getFPData: function(ix, id, flag) {
        var _this = this;
        this.Fp[ix] = {
          index: ix,
          id: id,
          flag: flag
        }
        _this.fpPut = [];

        hlhttp.get({
          url: 'bill/expenses',
          data: {
            bill_id: ACCOUNTID
          },
          success: function(res) {
						// ************ 营业额本次新增逻辑 start **********
						let amountReceivedRent = 0;  //固定租金金额
						let commissioAmount = 0;  //营业额金额
						let IsCompareRentAmtFlag = false; //判断是否是取其高
						res.map(item => {
							item.flag = true;
							item.styleFlag = false;
							if (item.expenseType == 'R') {
								amountReceivedRent = item.amountReceived;
							}
							if (item.expenseType == 'CM') {
								commissioAmount = item.amountReceived;
							}
						})
						if (_this.billData.compareRentAmtFlag && _this.billData.commissonConfirmFlag && _this.billData.commissionFlag) {
							if (_this.billData.compareRentAmtFlag == 'Y' && _this.billData.commissionFlag == 'Y' && _this.billData.commissonConfirmFlag == 'Y') {
								IsCompareRentAmtFlag = true;
							}
						}
						if (IsCompareRentAmtFlag) {
							res.map(item => {
								if (item.expenseType == 'CM') {
									if (item.amountReceived <= amountReceivedRent) {
										item.flag = false;
										item.styleFlag = true;
									}
								}
								if (item.expenseType == 'R') {
									if (item.amountReceived <= commissioAmount) {
										item.flag = false;
										item.styleFlag = true;
									}
								}
							})
						}
						// ************ 营业额本次新增逻辑 end *************
            _this.fPData = res;
            for (var i = 0; i < _this.fPData.length; i++) {
              _this.fpPut.push({
                a: '',
                b: ''
              })
              _this.jlFp.push({
                e: '',
                l: '',
                id: ''
              })
              _this.fPData[i].flag = false;
            }
            _this.fPIS = _this.billData.transactions[ix].amountTPay;
            _this.NIS = _this.billData.transactions[ix].amountTPay;
            _this.fpFlag = true;
          }
        })
      },
      
      //大图浏览
      getBigPic: function(img) {
        var temp = img ? img.split(',') : null;
        $.imageShow(temp)
      },
      //说明a
      getMemo: function(content, flag) {
        this.memo = {
          content: content,
          flag: flag
        }
      },
      
     

    },
    mounted: function() {
      this.getContractUnitsData()
      this.getBillData()
      this.getlogData()
    }
  })
}())
